rm(list=ls())
# Load data and results from main analysis
load("../Data/revealed.RData")
load("../Posteriors/ResultsVotes.RData")
cartype <- table(allmeps$postterm,allmeps$elsysopen1)
colnames(cartype) <- c("Party Centered","Candidate Centered")
row.names(cartype) <- c("European Career","National Career","Other")
print(xtable(cartype,   label = "tab:ambitionsinst",
             caption="Career Ambitions by Electoral Institutions",
             align="lcc"),
      caption.placement="top",table.placement = "htp",
      hline.after=0,file="ambitionsinst.tex",
          comment=F, add.to.row =  list(list(nrow(cartype)),  
            "\\hline \\multicolumn{3}{p{.8\\textwidth}}{\\textbf{Note:} \\small{\\textbf{Party Centered Systems:} Belgium, the Czech Republic, France, Germany, Greece (- 2009), Hungary, Latvia, the Netherlands, Poland, Portugal, Romania, Slovakia, Slovenia, Spain, and United Kingdom.\\newline \\textbf{Candidate Centered Systems:} Austria, Bulgaria, Croatia, Denmark, Greece (2014), Estonia, Ireland, Italy, Lithuania, Luxembourg, Malta, and Sweden.}} \\\\"))

carsys <- table(allmeps$postterm,allmeps$elsys)
colnames(carsys)[5] <- "SMP/STV"
row.names(carsys) <- c("European Career","National Career","Other")
print(xtable(carsys,   label = "tab:ambitionssystem",
             caption="Career Ambitions by Electoral System",
             align="lcccccc"),
      caption.placement="top",table.placement = "htp",
      hline.after=0,file="ambitionssystem.tex",
      comment=F, add.to.row =  list(list(nrow(carsys)),  
                                    "\\hline \\multicolumn{7}{p{.8\\textwidth}}{\\textbf{Note:} \\small{\\textbf{CLPR:} France, Germany, Greece ( - 2009), Hungary, Poland, Portugal, Romania, and Spain. \\newline \\textbf{CLPR/STV:} United Kingdom (European elections) \\newline \\textbf{OLPR:} Austria, Bulgaria (2014), Finland, Greece (2014), Italy, Lithunia, Luxembourg, and Sweden. \\newline \\textbf{Semi-OLPR:} Belgium, Bulgaria (- 2009), Croatia, Cyprus, the Czech Republic, Latvia, the Netherlands, Slovakia, and Slovenia. \\newline \\textbf{SMP:} United Kingdom (National elections). \\newline \\textbf{STV:} Ireland, and Malta.}} \\\\"))


#### Results function
outres <- function(resmat,dig=3){
n.models <- ncol(resmat)/3
outmat <- matrix(NA,ncol=n.models,nrow=2*nrow(resmat))
low <- seq(by=3,from = 2,to =3*n.models)
high <- seq(by=3,from=3,to =3*n.models)
res <- seq(by=3,from=1,to=3*n.models)
meat <- matrix(NA,ncol=n.models,nrow=nrow(resmat))
reslines <- seq(by=2,from=1,to=2*nrow(resmat))
conflines <-seq(by=2,from=2,to=2*nrow(resmat))
variables <- rep(NA,2*nrow(resmat))
variables[reslines] <- rownames(resmat)
  for (j in 1:n.models){
meat[,j] <- paste(round(resmat[,low[j]],digits=dig),round(resmat[,high[j]],digits=dig),sep=" , ")
meat[,j] <- ifelse(meat[,j]=="NA , NA",NA,paste("[",meat[,j],"]",sep=""))
  }
for (j in 1:n.models){
outmat[reslines,j] <- round(resmat[,res[j]],digits=dig)
outmat[conflines,j] <- meat[,j]
}
outmat <- cbind(variables,outmat)
return(outmat)
}
res <- function(tmp){
  tmp <- tmp
means <- apply(as.matrix(tmp),2,mean)
conf.int <- apply(as.matrix(tmp),2,quantile,probs=c(.025,.975))
out <- t(rbind(means,conf.int))
return(out)
}


# Participation in votes
all <- with(allmeps,aggregate(participation,by=list(postterm),FUN=mean))
candi <- with(allmeps[allmeps$elsysopen1==1,],aggregate(participation,by=list(postterm),FUN=mean))
party <- with(allmeps[allmeps$elsysopen1==0,],aggregate(participation,by=list(postterm),FUN=mean))
out <- cbind(all,candi$x,party$x)
colnames(out) <- c("","All","Candidate Centered","Party Centered")
out <- apply(out[,2:4],2,round,3)
row.names(out) <- c("European Career","National Career","Other")
print(xtable(out, label= "tab:votebyinst",
             caption="Participation in Roll Call Votes by Career Ambition, and Conditional on Electoral Institutions",
             align="lccc"),file="votebyinst.tex",table.placement = "htp",
      caption.placement="top",
      hline.after=0,
          comment=F, add.to.row =  list(list(nrow(out)),  
            "\\hline \\multicolumn{4}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Percentage of Roll Call Votes participated in, out of all roll call votes in the period each MEP served.}} \\\\"))

all <- with(allmeps,aggregate(participationByDay,by=list(postterm),FUN=mean))
candi <- with(allmeps[allmeps$elsysopen1==1,],aggregate(participationByDay,by=list(postterm),FUN=mean))
party <- with(allmeps[allmeps$elsysopen1==0,],aggregate(participationByDay,by=list(postterm),FUN=mean))
out <- cbind(all,candi$x,party$x)
colnames(out) <- c("","All","Candidate Centered","Party Centered")
out <- apply(out[,2:4],2,round,3)
row.names(out) <- c("European Career","National Career","Other")
print(xtable(out, label= "tab:votebyday",
             caption="Participation (days with rcvs), by Career Ambitions, and Conditional on Electoral Institutions",
             align="lccc"),file="votebyday.tex",table.placement = "htp",
      caption.placement="top",
      hline.after=0,
          comment=F, add.to.row =  list(list(nrow(out)),  
            "\\hline \\multicolumn{4}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Percentage of days with Roll Call Votes that MEPs voted in at least one roll-call vote, out of all days roll call votes in the period each MEP served.}} \\\\"))

# Results votes
load("../Posteriors/ResultsVotes.RData")
voteres <- as.mcmc.list(foo)
voteres <- res(voteres[,1:9])
vars <-  c("National (Candidate)","National (Party)","EU (Candidate)","EP incumbent","National background",
                    "Non-political career","Age","Leader (Group)","Leader (Committee)")
row.names(voteres) <- vars
load("../Posteriors/ResultsVotesDays.RData")
votedays <- as.mcmc.list(foo)
votedays <- res(votedays[,1:9])
row.names(votedays) <- vars
load("../Posteriors/ResultsVotesSystem.RData")
votesys <- as.mcmc.list(foo)
votesys <- res(votesys[,1:15])
sysvars <- c("CLPR (national)","CLPR (EP)","CLPR/STV (EP)","Semi-OLPR (National)","Semi-OLPR (EP)","STV (National)","STV (EP)",
             "OLPR (EP)","SMP/STV (National)","EP incumbent","National background","Non-political career","Age","Leader (Group)","Leader (Committee)")
row.names(votesys) <- sysvars
tmp <- merge(voteres,votedays,by="row.names",all=TRUE,sort=FALSE)
tmp <- merge(tmp,votesys,by.x="Row.names",by.y="row.names",all=TRUE,sort=FALSE)
row.names(tmp) <- tmp[,1]
votout <- outres(tmp[,-1])
groups <- c("Political group intercepts","Yes","Yes","Yes")
ms <- c("Member state intercepts","Yes","Yes","Yes")
terms <- c("EP intercept","Yes","Yes","Yes")
votout <- rbind(votout,groups,ms,terms)
colnames(votout) <- c(" ","Model 1","Model 2","Model 3")
votout <- ifelse(is.na(votout)," ",votout)
print(xtable(votout, label= "tab:voting",
             caption="Hierarchcial Binomial Models: Participation in Roll Call Votes",
             align="lcccc"),
      caption.placement="top",file="voting.tex",table.placement = "htp",
      hline.after=c(0,36,39),
      include.rownames=F,
          comment=F, add.to.row =  list(list(nrow(votout)),  
            "\\hline \\multicolumn{4}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Hierarchcial Binomial Models with random intercept for political groups, member states, and parliamentary term. Dependent Variable: Participation in Roll Call Votes (all, daily, all). Estimates are posterior mode and 95 percent posterior probabilty intervals.}} \\\\"))

# Resultfigure
library(arm)
load("../Posteriors/ResultsVotes.RData")
subeffects <- function(sims,vars){
tmp <- as.matrix(as.mcmc.list(sims))
out <- rowSums(tmp[,vars])
}
soc_Fr_eucar <- subeffects(sims=foo,vars=c("delta[1]","gamma[5]","nu[4]"))
soc_Fr_natcar <- subeffects(foo,c("delta[1]","gamma[5]","nu[4]","beta[2]")) 
epp_Ger_eucar <- subeffects(foo,c("delta[2]","gamma[6]","nu[4]")) 
epp_Ger_natcar <- subeffects(foo,c("delta[2]","gamma[6]","nu[4]","beta[2]")) 
epp_Fin_eucar <- subeffects(foo,c("delta[2]","gamma[4]","nu[4]","beta[3]")) 
epp_Fin_natcar <- subeffects(foo,c("delta[2]","gamma[4]","nu[4]","beta[1]")) 
soc_It_eucar <- subeffects(foo,c("delta[1]","gamma[9]","nu[4]","beta[3]")) 
soc_It_natcar <- subeffects(foo,c("delta[1]","gamma[9]","nu[4]","beta[1]")) 
# set transparent shades of grey
col1 <-rgb(0.2,0.2,0.2,0.5)
col2  <- rgb(0.8,0.8,0.8,0.5)
brk <- 15 # set bins
############
pdf("votingeffects.pdf")
par(mfrow = c(2,2),mar=c(5.1, 0.1, 4.1, 0.1))
ruler <- c(.42,.78)
hist(invlogit(soc_Fr_eucar),xlim=ruler,yaxt="n",ylab="",breaks=brk,
     main="Votes (Party Centered)",xlab="National vs European Career",sub="French Social Democrats EP 7")
hist(invlogit(soc_Fr_natcar),col=col1,add=TRUE,breaks=brk)
hist(invlogit(soc_Fr_eucar),col=col2,add=TRUE,breaks=brk)

hist(invlogit(epp_Ger_eucar),xlim=ruler,yaxt="n",ylab="",breaks=brk,
     main="Votes (Party Centered)",xlab="National vs European Career",sub="German Christian Democrats EP 7")
hist(invlogit(epp_Ger_natcar),col=col1,add=TRUE,breaks=brk)
hist(invlogit(epp_Ger_eucar),col=col2,add=TRUE,breaks=brk)
legend("topleft",legend=c("National","European"),col=c(col1,col2),lwd=4,bty="n")

hist(invlogit(soc_It_natcar),xlim=ruler,yaxt="n",ylab="",col=col1,breaks=brk,
     main="Votes (Candidate Centered)",xlab="National vs European Career",sub="Italian Social Democrats EP 7")
hist(invlogit(soc_It_eucar),col=col2,add=TRUE,breaks=brk)

hist(invlogit(epp_Fin_eucar),xlim=ruler,yaxt="n",ylab="",breaks=brk,
     main="Votes (candidate Centered)",xlab="National vs European Career",sub="Finnish Conservatives EP 7")
hist(invlogit(epp_Fin_natcar),col=col1,add=TRUE,breaks=brk)
hist(invlogit(epp_Fin_eucar),col=col2,add=TRUE,breaks=brk)
legend("topleft",legend=c("National","European"),col=c(col1,col2),lwd=4,bty="n")
dev.off()

## Participation in Debates
all <- with(allmeps,aggregate(participationSpeech,by=list(postterm),FUN=mean,na.rm=TRUE))
candi <- with(allmeps[allmeps$elsysopen1==1,],aggregate(participationSpeech,by=list(postterm),FUN=mean,na.rm=TRUE))
party <- with(allmeps[allmeps$elsysopen1==0,],aggregate(participationSpeech,by=list(postterm),FUN=mean,na.rm=TRUE))
out <- cbind(all,candi$x,party$x)
colnames(out) <- c(" ","All","Candidate Centered","Party Centered")
out <- apply(out[,2:4],2,round,3)
row.names(out) <- c("European Career","National Career","Other")
print(xtable(out, label= "tab:descdebates",
             caption="Participation in Plenary Debates, by Career Ambition, and Conditional on Electoral Institutions",
             align="lccc"),
      caption.placement="top",
      hline.after=0,file="descdebates.tex",table.placement = "htp",
          comment=F, add.to.row =  list(list(nrow(out)),  
            "\\hline \\multicolumn{4}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Percentage of days with debates MEPs participated in, out of all days with debates in the period each MEP served.}} \\\\"))

# Debates
load("../Posteriors/ResultsDebatesAll.RData")
debres <- as.mcmc.list(fooDebates)
debres <- res(debres[,1:9])
row.names(debres) <- vars
load("../Posteriors/ResultsDebates.RData")
debdays <- as.mcmc.list(fooDebates)
debdays <- res(debdays[,1:9])
row.names(debdays) <- vars
load("../Posteriors/ResultsDebatesSystem.RData")
debsys <- as.mcmc.list(fooDebates)
debsys <- res(debsys[,1:15])
row.names(debsys) <- sysvars
tmp <- merge(debres,debdays,by="row.names",all=TRUE,sort=FALSE)
tmp <- merge(tmp,debsys,by.x="Row.names",by.y="row.names",all=TRUE,sort=FALSE)
row.names(tmp) <- tmp[,1]
debout <- outres(tmp[,-1])
debout <- rbind(debout,groups,ms,terms)
colnames(debout) <- c(" ","Model 4","Model 5","Model 6")
debout <- ifelse(is.na(debout)," ",debout)

print(xtable(debout, label= "tab:debates",
             caption="Hierarchcial Binomial Models: Participation in Debates",
             align="lcccc"),
      caption.placement="top",
      hline.after=c(0,36,39),
      table.placement ="htp",
      include.rownames=F,file="debates.tex",
          comment=F, add.to.row =  list(list(nrow(debout)),  
            "\\hline \\multicolumn{4}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Hierarchcial Binomial Models with random intercept for political groups, member states, and parliamentary term. Dependent Variable: Dependent variable: particiaption in debates (all, at least once that day, at least once that day). Estimates are posterior mode and 95 percent posterior probabilty intervals.}} \\\\"))

# substantive debates effects
load("../Posteriors/ResultsDebatesAll.RData")
soc_Fr_eucar <- subeffects(sims=fooDebates,vars=c("delta[1]","gamma[5]","nu[3]"))
soc_Fr_natcar <- subeffects(fooDebates,c("delta[1]","gamma[5]","nu[3]","beta[2]")) 
epp_Ger_eucar <- subeffects(fooDebates,c("delta[2]","gamma[6]","nu[3]")) 
epp_Ger_natcar <- subeffects(fooDebates,c("delta[2]","gamma[6]","nu[3]","beta[2]")) 
epp_Fin_eucar <- subeffects(fooDebates,c("delta[2]","gamma[4]","nu[3]","beta[3]")) 
epp_Fin_natcar <- subeffects(fooDebates,c("delta[2]","gamma[4]","nu[3]","beta[1]")) 
soc_It_eucar <- subeffects(fooDebates,c("delta[1]","gamma[9]","nu[3]","beta[3]")) 
soc_It_natcar <- subeffects(fooDebates,c("delta[1]","gamma[9]","nu[3]","beta[1]")) 

pdf("debateeffects.pdf")
par(mfrow = c(2,2),mar=c(5.1, 0.1, 4.1, 0.1))
brk <- 50 # set bins
ruler <- c(0,1)
hist(invlogit(soc_Fr_eucar),xlim=ruler,yaxt="n",ylab="",breaks=brk,
     main="Debates (Party Centered)",xlab="National vs European Career",sub="French Social Democrats EP 7")
hist(invlogit(soc_Fr_natcar),col=col1,add=TRUE,breaks=brk)
hist(invlogit(soc_Fr_eucar),col=col2,add=TRUE,breaks=brk)
legend("topleft",legend=c("National","European"),col=c(col1,col2),lwd=4,bty="n")

hist(invlogit(epp_Ger_natcar),xlim=ruler,yaxt="n",ylab="",col=col1,breaks=brk,
     main="Debates (Party Centered)",xlab="National vs European Career",sub="German Christian Democrats EP 7")
hist(invlogit(epp_Ger_eucar),col=col2,add=TRUE,breaks=brk)

hist(invlogit(soc_It_natcar),xlim=ruler,yaxt="n",ylab="",breaks=brk,col=col1,
     main="Debates (Candidate Centered)",xlab="National vs European Career",sub="Italian Social Democrats EP 7")
hist(invlogit(soc_It_eucar),col=col2,add=TRUE,breaks=brk)
legend("topleft",legend=c("National","European"),col=c(col1,col2),lwd=4,bty="n")

hist(invlogit(epp_Fin_natcar),xlim=ruler,yaxt="n",ylab="",col=col1,breaks=brk,
     main="Debates (Candidate Centered)",xlab="National vs European Career",sub="Finnish Conservatives EP 7")
hist(invlogit(epp_Fin_eucar),col=col2,add=TRUE,breaks=brk)
dev.off()

# Stated Career Ambitions
load("../Data/survey.RData")
all <- with(outdata,aggregate(participation,by=list(future),FUN=mean))
candi <- with(outdata[outdata$elsysopen1==1,],aggregate(participation,by=list(future),FUN=mean))
party <- with(outdata[outdata$elsysopen1==0,],aggregate(participation,by=list(future),FUN=mean))
out <- cbind(all,candi$x,party$x)
colnames(out) <- c("","All","Candidate Centered","Party Centered")
out <- apply(out[,2:4],2,round,3)
row.names(out) <- c("European Career","National Career","Other")
print(xtable(out, label= "tab:descsurveyvotes",
             caption="Survey: Future Career, Electoral Institutions, and Particiaption in Votes",
             align="lccc"),
      caption.placement="top",
      hline.after=0,file="descsurveyvotes.tex",table.placement="htp",
          comment=F, add.to.row =  list(list(nrow(out)),  
            "\\hline \\multicolumn{4}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Percentage of days with Roll Call Votes that MEPs voted in at least one roll-call vote, out of all days roll call votes in the period each MEP served.}} \\\\"))

all <- with(outdata,aggregate(participationSpeech,by=list(future),FUN=mean))
candi <- with(outdata[outdata$elsysopen1==1,],aggregate(participationSpeech,by=list(future),FUN=mean))
party <- with(outdata[outdata$elsysopen1==0,],aggregate(participationSpeech,by=list(future),FUN=mean))
out <- cbind(all,candi$x,party$x)
colnames(out) <- c("","All","Candidate Centered","Party Centered")
out <- apply(out[,2:4],2,round,3)
row.names(out) <- c("European Career","National Career","Other")
print(xtable(out, label= "tab:descsurveydebates",
             caption="Survey: Future Career, Electoral Institutions, and Particiaption in Debates",
             align="lccc"),
      caption.placement="top",
      hline.after=0,file="descsurveydebates.tex",table.placement="htp",
          comment=F, add.to.row =  list(list(nrow(out)),  
            "\\hline \\multicolumn{4}{p{.8\\textwidth}}{\\textbf{Note:} \\small{  Percentage of days with debates MEPs participated in, out of all days with debates in the period each MEP served. }} \\\\"))
#

# Survey voting
load("../Posteriors/ResultsVotesSurv.RData")
survvotes <- as.mcmc.list(foo)
survvotes <- res(survvotes[,1:9])
row.names(survvotes) <- vars
load("../Posteriors/ResultsDebatesSurv.RData")
survdebates <- as.mcmc.list(fooDebates)
survdebates <- res(survdebates[,1:9])
row.names(survdebates) <- vars
tmp <- merge(survvotes,survdebates,by="row.names",sort=FALSE)
row.names(tmp) <- tmp[,1]
survout <- outres(tmp[,-1])
survout <- rbind(survout,groups[-4],ms[-4],terms[-4])
colnames(survout) <- c(" ","Model 7","Model 8")
survout <- ifelse(is.na(survout)," ",survout)

print(xtable(survout, label= "tab:surveyresults",
             caption="Hierarical binomial models. Survey: Votes and Speeches",
             align="lccc"),
      caption.placement="top",
      hline.after=c(0,18,21),
      table.placement ="htp",file="surveyresults.tex",
      include.rownames=F,
          comment=F, add.to.row =  list(list(nrow(survout)),  
            "\\hline \\multicolumn{3}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Hierarchcial Binomial Models with random intercept for political groups, member states, and parliamentary term. Dependent Variable: Participation in Roll Call Votes (Model 7) and in debates (Model 8). Estimates are posterior mode and 95 percent posterior probabilty intervals.}} \\\\"))

# plot survey effects
load("../Posteriors/ResultsVotesSurv.RData")
epp_Fr_eucar <- subeffects(foo,c("delta[3]","gamma[2]","nu[3]")) 
epp_Fr_natcar <- subeffects(foo,c("delta[3]","gamma[2]","nu[3]","beta[2]")) 
epp_It_eucar <- subeffects(foo,c("delta[3]","gamma[10]","nu[3]","beta[3]")) 
epp_It_natcar <- subeffects(foo,c("delta[3]","gamma[10]","nu[3]","beta[1]")) 

pdf("surveyeffects.pdf")
par(mfcol = c(2,3),mar=c(5.1, 0.1, 4.1, 0.1))
brk <- 15
ruler <- c(.25,.85)
hist(invlogit(soc_Fr_eucar),xlim=ruler,yaxt="n",ylab="",breaks=brk,
     main="Votes (Party Centered)",xlab="Survey: National vs European Career",sub="French Christian Democrats EP 7")
hist(invlogit(soc_Fr_natcar),col=col1,add=TRUE,breaks=brk)
hist(invlogit(soc_Fr_eucar),col=col2,add=TRUE,breaks=brk)

hist(invlogit(epp_It_natcar),xlim=ruler,yaxt="n",ylab="",breaks=brk,col=col1,
     main="Votes (Candidate Centered)",xlab="National vs European Career",sub="Italian Christian Democrats EP 7")
hist(invlogit(epp_It_eucar),col=col2,add=TRUE,breaks=brk)

load("../Posteriors/ResultsDebatesSurv.RData")
epp_Fr_eucar <- subeffects(fooDebates,c("delta[3]","gamma[2]","nu[3]")) 
epp_Fr_natcar <- subeffects(fooDebates,c("delta[3]","gamma[2]","nu[3]","beta[2]")) 
epp_It_eucar <- subeffects(fooDebates,c("delta[3]","gamma[10]","nu[3]","beta[3]")) 
epp_It_natcar <- subeffects(fooDebates,c("delta[3]","gamma[10]","nu[3]","beta[1]")) 
brk <- 50
ruler <- c(.55,1)
hist(invlogit(epp_Fr_natcar),xlim=ruler,yaxt="n",ylab="",breaks=brk,col=col1,
     main="Debates (Party Centered)",xlab="Survey: National vs European Career",sub="French Christian Democrats EP 7")
hist(invlogit(epp_Fr_eucar),col=col2,add=TRUE,breaks=brk)
legend("topleft",legend=c("National","European"),col=c(col1,col2),lwd=4,bty="n")

hist(invlogit(epp_It_natcar),xlim=ruler,yaxt="n",ylab="",breaks=brk,col=col1,
     main="Debates (Candidate Centered)",xlab="National vs European Career",sub="Italian Christian Democrats EP 7")
hist(invlogit(epp_It_eucar),col=col2,add=TRUE,breaks=brk)
legend("topleft",legend=c("National","European"),col=c(col1,col2),lwd=4,bty="n")
dev.off()

# appendix models
outres <- function(resmat,dig=3){
  n.models <- ncol(resmat)/3
  outmat <- matrix(NA,ncol=n.models,nrow=2*nrow(resmat))
  low <- seq(by=3,from = 2,to =3*n.models)
  high <- seq(by=3,from=3,to =3*n.models)
  res <- seq(by=3,from=1,to=3*n.models)
  meat <- matrix(NA,ncol=n.models,nrow=nrow(resmat))
  reslines <- seq(by=2,from=1,to=2*nrow(resmat))
  conflines <-seq(by=2,from=2,to=2*nrow(resmat))
  variables <- rep(NA,2*nrow(resmat))
  variables[reslines] <- rownames(resmat)
  for (j in 1:n.models){
    meat[,j] <- paste(round(resmat[,low[j]],digits=dig),round(resmat[,high[j]],digits=dig),sep=" , ")
    meat[,j] <- ifelse(meat[,j]=="NA , NA",NA,paste("[",meat[,j],"]",sep=""))
  }
  for (j in 1:n.models){
    outmat[reslines,j] <- round(resmat[,res[j]],digits=dig)
    outmat[conflines,j] <- meat[,j]
  }
  outmat <- cbind(variables,outmat)
  return(outmat)
}
res <- function(tmp){
  tmp <- tmp
  means <- apply(as.matrix(tmp),2,mean)
  conf.int <- apply(as.matrix(tmp),2,quantile,probs=c(.025,.975))
  out <- t(rbind(means,conf.int))
  return(out)
}

# legislative votes
load("../Posteriors/ResultsVotesLegis.RData")
voteres <- as.mcmc.list(foo)
voteres <- res(voteres[,1:9])
vars <-  c("National (Candidate)","National (Party)","EU (Candidate)","EP incumbent","National background",
           "Non-political career","Age","Leader (Group)","Leader (Committee)")
row.names(voteres) <- vars
load("../Posteriors/ResultsVotesLegisDays.RData")
votedays <- as.mcmc.list(foo)
votedays <- res(votedays[,1:9])
row.names(votedays) <- vars
load("../Posteriors/ResultsVotesLegisSystem.RData")
votesys <- as.mcmc.list(foo)
votesys <- res(votesys[,1:15])
sysvars <- c("CLPR (national)","CLPR (EP)","CLPR/STV (EP)","Semi-OLPR (National)","Semi-OLPR (EP)","STV (National)","STV (EP)",
             "OLPR (EP)","SMP/STV (National)","EP incumbent","National background","Non-political career","Age","Leader (Group)","Leader (Committee)")
row.names(votesys) <- sysvars

load("../Posteriors/ResultsVotesLegisSurv.RData")
survvotes <- as.mcmc.list(foo)
survvotes <- res(survvotes[,1:9])
row.names(survvotes) <- vars

tmp <- merge(voteres,votedays,by="row.names",all=TRUE,sort=FALSE)
tmp <- merge(tmp,votesys,by.x="Row.names",by.y="row.names",all=TRUE,sort=FALSE)
tmp <- merge(tmp,survvotes,by.x="Row.names",by.y="row.names",all=TRUE,sort=FALSE)
row.names(tmp) <- tmp[,1]
votout <- outres(tmp[,-1])
groups <- c("Political group intercepts","Yes","Yes","Yes","Yes")
ms <- c("Member state intercepts","Yes","Yes","Yes","Yes")
terms <- c("EP intercept","Yes","Yes","Yes","Yes")
votout <- rbind(votout,groups,ms,terms)
colnames(votout) <- c(" ","Model A1","Model A2","Model A3","Model A4")
votout <- ifelse(is.na(votout)," ",votout)
print(xtable(votout, label= "tab:votingLegis",
             caption="Hierarchcial Binomial Models: Participation in Legislative Roll Call Votes",
             align="lccccc"),
      caption.placement="top",
      hline.after=c(0,36,39),
      table.placement ="htp",file="votingLegis.tex",
      include.rownames=F,
      comment=F, add.to.row =  list(list(nrow(votout)),  
                                    "\\hline \\multicolumn{5}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Hierarchcial Binomial Models with random intercept for political groups, member states, and parliamentary term. Dependent Variable: Participation in Legislative Roll Call Votes (all, daily, all,survey). Estimates are posterior mode and 95 percent posterior probabilty intervals.}} \\\\"))

# close votes
load("../Posteriors/ResultsVotesLegis.RData")
voteres <- as.mcmc.list(foo)
voteres <- res(voteres[,1:9])
vars <-  c("National (Candidate)","National (Party)","EU (Candidate)","EP incumbent","National background",
           "Non-political career","Age","Leader (Group)","Leader (Committee)")
row.names(voteres) <- vars
load("../Posteriors/ResultsVotesCloseDays.RData")
votedays <- as.mcmc.list(foo)
votedays <- res(votedays[,1:9])
row.names(votedays) <- vars
load("../Posteriors/ResultsVotesCloseSystem.RData")
votesys <- as.mcmc.list(foo)
votesys <- res(votesys[,1:15])
sysvars <- c("CLPR (National)","CLPR (EP)","CLPR/STV (EP)","Semi-OLPR (National)","Semi-OLPR (EP)","STV (National)","STV (EP)",
             "OLPR (EP)","SMP/STV (National)","EP incumbent","National background","Non-political career","Age","Leader (Group)","Leader (Committee)")
row.names(votesys) <- sysvars
load("../Posteriors/ResultsVotesCloseSurv.RData")
survvotes <- as.mcmc.list(foo)
survvotes <- res(survvotes[,1:9])
row.names(survvotes) <- vars

tmp <- merge(voteres,votedays,by="row.names",all=TRUE,sort=FALSE)
tmp <- merge(tmp,votesys,by.x="Row.names",by.y="row.names",all=TRUE,sort=FALSE)
tmp <- merge(tmp,survvotes,by.x="Row.names",by.y="row.names",all=TRUE,sort=FALSE)
row.names(tmp) <- tmp[,1]
votout <- outres(tmp[,-1])
groups <- c("Political group intercepts","Yes","Yes","Yes","Yes")
ms <- c("Member state intercepts","Yes","Yes","Yes","Yes")
terms <- c("EP intercept","Yes","Yes","Yes","Yes")
votout <- rbind(votout,groups,ms,terms)

colnames(votout) <- c(" ","Model A5","Model A6","Model A7","Model A8")
votout <- ifelse(is.na(votout)," ",votout)
print(xtable(votout, label= "tab:votingClose",
             caption="Hierarchcial Binomial Models: Participation in Close Roll Call Votes",
             align="lccccc"),
      caption.placement="top",
      hline.after=c(0,36,39),
      table.placement ="htp",file="votingClose.tex",
      include.rownames=F,
      comment=F, add.to.row =  list(list(nrow(votout)),  
                                    "\\hline \\multicolumn{5}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Hierarchcial Binomial Models with random intercept for political groups, member states, and parliamentary term. Dependent Variable: Participation in close Roll Call Votes (all, daily, all,survey). Estimates are posterior mode and 95 percent posterior probabilty intervals.}} \\\\"))

### National party random effects
load("../Posteriors/ResultsVotesNat.RData")
load("../Posteriors/ResultsDebatesNat.RData")
voteres <- res(resVotes[,1:9])
vars <-  c("National (Candidate)","National (Party)","EU (Candidate)","EP incumbent","National background",
           "Non-political career","Age","Leader (Group)","Leader (Committee)")
row.names(voteres) <- vars

debateres <- res(resDebates[,1:9])
row.names(debateres) <- vars

tmp <- merge(voteres,debateres,by="row.names",all=TRUE,sort=FALSE)
row.names(tmp) <- tmp[,1]
votout <- outres(tmp[,-1])
terms <- c("EP intercept","Yes","Yes")
natparties <- c("National parties intercept","Yes","Yes")
natout <- rbind(votout,terms,natparties)
colnames(natout) <- c(" ","Model A9","Model A10")
natout <- ifelse(is.na(natout)," ",natout)
print(xtable(natout, label= "tab:natparties",
             caption="Hierarchcial Binomial Models: National parties random effects",
             align="lccc"),
      caption.placement="top",
      hline.after=c(0,18,20),
      table.placement ="htp",file="Natparties.tex",
      include.rownames=F,
      comment=F, add.to.row =  list(list(nrow(natout)),  
                                    "\\hline \\multicolumn{3}{p{.8\\textwidth}}{\\textbf{Note:} \\small{ Hierarchcial Binomial Models with random intercept for national parties and parliamentary term. Dependent Variable: Participation in Roll Call Votes / Participation in Debates. Estimates are posterior mode and 95 percent posterior probabilty intervals.}} \\\\"))


